Dart Map operator []
Syntax & Examples
Syntax of Map.operator []
The syntax of Map.operator [] operator is:
operator [](Object? key) → V?This operator [] operator of Map the value for the given key, or null if key is not in the map.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
key | required | The key for which to retrieve the corresponding value. |
✐ Examples
1 Retrieve value for key 'b'
In this example,
- We create a map named
mapwith key-value pairs. - We then use the
[]operator to retrieve the value associated with the key'b'. - The value corresponding to key
'b'is retrieved. - We print the value to standard output.
Dart Program
void main() {
var map = {'a': 1, 'b': 2, 'c': 3};
var value = map['b'];
print(value);
}Output
2
2 Retrieve value for key 'z'
In this example,
- We create a map named
mapwith key-value pairs. - We then use the
[]operator to retrieve the value associated with the key'z'. - The value corresponding to key
'z'is retrieved. - We print the value to standard output.
Dart Program
void main() {
var map = {'x': 'A', 'y': 'B', 'z': 'C'};
var value = map['z'];
print(value);
}Output
C
3 Retrieve value for key 'vegetable'
In this example,
- We create a map named
mapwith key-value pairs. - We then use the
[]operator to retrieve the value associated with the key'vegetable'. - The value corresponding to key
'vegetable'is retrieved. - We print the value to standard output.
Dart Program
void main() {
var map = {'fruit': 'apple', 'vegetable': 'carrot', 'grain': 'rice'};
var value = map['vegetable'];
print(value);
}Output
carrot
Summary
In this Dart tutorial, we learned about operator [] operator of Map: the syntax and few working examples with output and detailed explanation for each example.